package com.cdgeekcamp.redas.wechat.controller;

import com.cdgeekcamp.redas.wechat.entity.WeChatMenu;
import com.cdgeekcamp.redas.wechat.factory.WeChatMenuFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

@RestController
@RequestMapping(value = "/weChat")
public class CreateMenu {

    /**
     * 创建微信自定义菜单
     * @param accessToken
     */
    @GetMapping(value = "/createMenu")
    public void createWeChatMenu(@RequestParam("access_token") String accessToken){
        String url = String.format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", accessToken);

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        // 菜单
        ArrayList<WeChatMenu> list = new WeChatMenuFactory().getMenu();

        HashMap<String, ArrayList<WeChatMenu>> map = new HashMap<String, ArrayList<WeChatMenu>>();
        map.put("button", list);


        HttpEntity<HashMap<String, ArrayList<WeChatMenu>>> httpEntity = new HttpEntity<>(map, httpHeaders);

        try{
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            if (responseEntity.getStatusCodeValue() != 200){
                throw new RestClientException("创建菜单,请求失败");
            }else {
                System.out.println(responseEntity.getBody());
            }
        }catch (RestClientException e) {
            e.printStackTrace();
        }
    }
}
